package com.jh.user.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.business.UserRealtionBusiness;
import com.jh.user.business.UserRelationBusiness;
import com.jh.user.pojo.Brand;
import com.jh.user.pojo.ChannelRate;
import com.jh.user.pojo.User;
import com.jh.user.pojo.UserRealtion;
import com.jh.user.util.Util;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.ExceptionUtil;

@Controller
@EnableAutoConfiguration
public class UserRelationService {
	
	private final Logger LOG = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private Util util;
	
	@Autowired
	private UserLoginRegisterBusiness userLoginRegisterBusiness;
	
	@Autowired
	private UserRealtionBusiness userRealtionBusiness;
	
	@Autowired
	private UserRelationBusiness userRelationBusiness;
	
	@Autowired
	private ChannelService channelService;
	
	@Autowired
	 private RedisTemplate redisTemplate;
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/test")
	public @ResponseBody Object addUserRealtion() throws Exception{
		userRealtionBusiness.addRealtion();
		return "OK";
	}
	
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/query/preuser")
	public @ResponseBody Object getUsersPreUserGradeAndRate(HttpServletRequest request,
			@RequestParam(value="userId")String userId,
			@RequestParam(value="channelId")String channelId
			){
		Map<String,Object> map = new HashMap<>();
		List<UserRealtion> userRealtions = userRealtionBusiness.findByFirstUserId(Long.valueOf(userId));
		if(userRealtions.size() != 0){
			for(UserRealtion userRealtion:userRealtions){
				long preUserId = userRealtion.getPreUserId();
				@SuppressWarnings("unchecked")
				Map<String,Object> reateMap = (Map<String, Object>) channelService.queryChannelRateByuserid(request,preUserId, Long.valueOf(channelId),"rebate");
				if(CommonConstants.SUCCESS.equals(reateMap.get(CommonConstants.RESP_CODE))){
					ChannelRate channelRate = new ChannelRate();
					try {
						BeanUtils.copyProperties(channelRate, reateMap.get(CommonConstants.RESULT));
					} catch (IllegalAccessException | InvocationTargetException e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						continue;
					}
					LOG.info("用户费率================:" + channelRate);
					userRealtion.setRate(channelRate.getRate());
				}
			}
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			Map<String,List> userRealtionMap = new HashMap<String,List>();
			userRealtionMap.put(CommonConstants.RESULT, userRealtions);
			map.put(CommonConstants.RESULT,userRealtionMap);
		}else{
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功,但无上级数据");
		}
		return map;
	}
	
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/add/one/user")
	public @ResponseBody Object addOneUserRealtion(HttpServletRequest request,
			@RequestParam(value="userId")String userId
			) throws Exception{
		Map<String,Object> map = new HashMap<>();
		User user = userLoginRegisterBusiness.queryUserById(Long.valueOf(userId));
		if(user != null){
			userRealtionBusiness.addOneUserRealtion(user);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "添加成功");
		}else{
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "添加失败,无该用户");
		}
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/update/user/parente")
	public @ResponseBody Object updateOneUserPerUser(
			@RequestParam(value="oriPhone")String oriPhone,
			@RequestParam(value="brandId")String brandId,
			@RequestParam(value="prePhone")String prePhone
			){
		Map<String,Object> map = new HashMap<>();
		/*if(true) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该功能正在升级！！！！！！！！");
			return map;
		}*/
		
		
		oriPhone = oriPhone.trim();
		prePhone = prePhone.trim();
		boolean hasKey = false;
		String key = "/v1.0/user/realtion/update/user/parente:oriPhone=" + oriPhone + ";prePhone=" + prePhone + ";brandId=" + brandId;
		ValueOperations<String, String> operations = redisTemplate.opsForValue();
		hasKey = redisTemplate.hasKey(key);
		if(hasKey){
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "正在转移上下级关系,请等待!");
			return map;
		}
		User oriUser = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(oriPhone, Long.valueOf(brandId));
		User preUser = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(prePhone, Long.valueOf(brandId));
		
		if(oriPhone.equals(prePhone)){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "手机号不能相等!");
			return map;
		}
		
		if(oriUser == null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询不到要更改用户");
			return map;
		}else if(preUser == null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询不到上级用户");
			return map;
		}
		System.out.println(oriUser);
		if(oriUser.getPreUserPhone().equals(prePhone)){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "已经是该用户下级,无需再修改!");
			return map;
		}
		operations.set(key, key,600,TimeUnit.SECONDS);
		List<UserRealtion> oriUserRealtions = userRealtionBusiness.findByPreUserId(oriUser.getId());
		List<Long> sonUserIds = new ArrayList<>();
		if(oriUserRealtions != null && oriUserRealtions.size() >0 ){
			for(UserRealtion userRealtion:oriUserRealtions){
				if(preUser.getId() == userRealtion.getFirstUserId()){
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "该上级用户是要更改用户的下级,无法进行调整!");
					return map;
				}
				sonUserIds.add(userRealtion.getFirstUserId());
			}
		}
		oriUser.setPreUserId(preUser.getId());
		oriUser.setPreUserPhone(preUser.getPhone());
		try {
			userRealtionBusiness.deleteAndRebuildUserRealtion(oriUser,sonUserIds);
		} catch (Exception e) {
			e.printStackTrace();
			redisTemplate.delete(key);
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "修改失败");
			return map;
		}
		redisTemplate.delete(key);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "修改成功");
		map.put(CommonConstants.RESULT, oriUser);
		return map;
	}
	
	/**
	 * 将一个新用户转换成贴牌商,并删除上下级关系
	 * @param phone
	 * @param brandId
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/update/to/branduser")
	public @ResponseBody Object updateUserToBrandUser(
			@RequestParam(value="phone")String phone,
			@RequestParam(value="brandId")String brandId
			){
		Map<String,Object> map = new HashMap<>();
		User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, Long.valueOf(brandId));
		if(user != null){
			try {
				userRealtionBusiness.updateUserToBrandUser(user);
			} catch (Exception e) {
				e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "修改失败");
				return map;
			}
		}else{
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查不到该用户数据!");
			return map;
		}
		
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "设置贴牌用户成功!");
		return map;
	}
	
	/**
	 * 将用户变为贴牌商,删除所有上级关系,并更新下级的上级关系
	 * @param phone
	 * @param brandId
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/update/to/branduser2")
	public @ResponseBody Object updateUserToBrandUser2(
			@RequestParam(value="phone")String phone,
			@RequestParam(value="brandId")String brandId
			) {
		Map<String,Object> map = new HashMap<>();
		User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, Long.valueOf(brandId));
		if(user != null){
			try {
				userRealtionBusiness.updateUserToBrandUser2(user);
			} catch (Exception e) {
				e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "修改失败");
				return map;
			}
		}else{
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查不到该用户数据!");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "设置贴牌用户成功!");
		return map;
	}
	
	/**
	 * 查询指定user的所有下级
	 * @param userId
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/find/user/all/sons")
	public @ResponseBody Object findSonUserByUserId(
			@RequestParam(value="userId")String userId
			){
		Map<String,Object> map = new HashMap<>();
		List<UserRealtion> sonUserRealtions = userRealtionBusiness.findByPreUserId(Long.valueOf(userId));
		if(sonUserRealtions != null && sonUserRealtions.size() > 0){
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, sonUserRealtions);
		}else{
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功,但无下级用户");
		}
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/find/user/all/parent")
	public @ResponseBody Object findParentUserByUserId(
			@RequestParam(value="userId")String userId
			){
		Map<String,Object> map = new HashMap<>();
		List<UserRealtion> parentUserRealtions = userRealtionBusiness.findByFirstUserId(Long.valueOf(userId));
		if(parentUserRealtions != null && parentUserRealtions.size() > 0){
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, parentUserRealtions);
		}else{
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功,但无下级用户");
		}
		return map;
	}
	
	
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/realtion/find/user/member/byphone")
	public @ResponseBody Object queryUserRelationByUserId(HttpServletRequest request,
			@RequestParam(value = "phone") String phone,
			@RequestParam(value = "start_time", required = false) String startTime,
			@RequestParam(value = "end_time", required = false) String endTime,
			@RequestParam(value = "level", required = false, defaultValue = "1") String level
			) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
//		Date StartTimeDate = null;
//		try {
//			if (startTime != null && !startTime.trim().equalsIgnoreCase("")) {
//				StartTimeDate = DateUtil.getDateFromStr(startTime);
//			}
//		} catch (Exception e1) {
//			LOG.error("startTime转换异常===========================" + e1);
//			startTime = null;
//		}
//		Date endTimeDate = null;
//
//		try {
//			if (endTime != null && !endTime.trim().equalsIgnoreCase("")) {
//				endTimeDate = DateUtil.getDateFromStr(endTime);
//			}
//		} catch (Exception e) {
//			LOG.error("endTime转换异常============================" + e);
//			endTime = null;
//		}
		
		List<Long> findUserAgentChangeByTimeAndPhone = null;
		List<Long> findUserAgentChangeByTimeAndPhoneAndLevel = null;
		try {
			findUserAgentChangeByTimeAndPhone = userRelationBusiness.findUserAgentChangeByTimeAndPhone(startTime, endTime, phone);
			
			findUserAgentChangeByTimeAndPhoneAndLevel = userRelationBusiness.findUserAgentChangeByTimeAndPhoneAndLevel(startTime, endTime, phone, level);
		} catch (Exception e) {
			LOG.error("查询直推和间推会员失败======");
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询失败");
		}
		
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put("list1", findUserAgentChangeByTimeAndPhone);
		map.put("list2", findUserAgentChangeByTimeAndPhoneAndLevel);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		
		return map;
	}

}
